<!DOCTYPE html>

<html lang="zh-Hans">
  <head>
    <meta charset="utf-8" />
    <meta name="author" content="rogepi" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="/vue.global.js"></script>
    <title>6-todo-list</title>
  </head>

  <body>
    <div id="todo-list-example">
      <form v-on:submit.prevent="addNewTodo">
        <label for="new-todo">Add a todo</label>
        <input
          v-model="newTodoText"
          id="new-todo"
          placeholder="E.g. Feed the cat"
        />
        <button>Add</button>
        <ul>
          <todo-item
            v-for="(todo,index) in todos"
            :key="todo.id"
            :title="todo.title"
            @remove="todos.splice(index,1)"
          ></todo-item>
        </ul>
      </form>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            newTodoText: '',
            todos: [
              {
                id: 1,
                title: 'Do the dishes',
              },
              {
                id: 2,
                title: 'Take out the trash',
              },
              {
                id: 3,
                title: 'Mow the lawn',
              },
            ],
            nextTodoId: 4,
          };
        },
        methods: {
          addNewTodo() {
            this.todos.push({
              id: this.nextTodoId++,
              title: this.newTodoText,
            });
            this.newTodoText = '';
          },
        },
      });

      app.component('todo-item', {
        template: `
                    <li>
                      {{ title }}
                      <button @click="$emit('remove')">Remove</button>
                    </li>
                  `,
        props: ['title'],
        emits: ['remove'],
      });

      app.mount('#todo-list-example');
    </script>
  </body>
</html>
